// 蜂窝蜜造平台生成代码，如手工更改，请添加到 .beeignore 忽略生成

package com.fowo.api.costAccounting.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fowo.api.common.model.ImportRow;
import com.fowo.api.common.model.RException;
import com.fowo.api.common.util.ResponseUtils;
import com.fowo.api.common.util.SheetUtils;
import com.fowo.api.costAccounting.entity.MonthlyCostReport;
import com.fowo.api.costAccounting.mapper.MonthlyCostReportMapper;
import com.fowo.api.costAccounting.model.monthly.MonthlyCostReportExcelPo;
import com.fowo.api.costAccounting.model.monthly.MonthlyCostReportImportPo;
import com.fowo.api.costAccounting.model.monthly.MonthlyCostReportItemVo;
import com.fowo.api.costAccounting.model.monthly.MonthlyCostReportSearchParamPo;
import com.fowo.api.costAccounting.model.monthly.MonthlyCostReportVo;
import com.fowo.api.costAccounting.model.stock.StockVo;
import com.fowo.api.costAccounting.service.MonthlyCostReportService;
import com.fowo.api.sys.entity.SysFile;
import com.fowo.api.sys.service.FileService;
import com.fowo.api.user.model.JwtUserInfo;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 成本月报 服务实现类
 */
@Service
@Slf4j
public class MonthlyCostReportServiceImpl
        extends ServiceImpl<MonthlyCostReportMapper, MonthlyCostReport>
        implements MonthlyCostReportService {

  public static final Map<String, String> SORT_FIELD_MAP = new HashMap<>();
  // 导出时单次查询最大记录数
  protected static final int EXPORT_QUERY_MAX_SIZE = 1000;
  // 支持导出的最大记录数(1048576 为 Excel 支持的最大行数)
  protected static final long EXPORT_MAX_SIZE = 1048575;

  @Resource
  protected FileService fileService;

  @Resource
  protected Validator validator;

  /**
   * 创建成本月报
   * @param model 成本月报
   * @return 新数据的主键
   */
  @Transactional(rollbackFor = Exception.class)
  @Override
  public Long create(MonthlyCostReportVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    MonthlyCostReport entity = new MonthlyCostReport();
    BeanUtils.copyProperties(model, entity);
    entity.setCreateTime(new Date());
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setCreateUser(currentUser.getUserId());
      entity.setLastUpdateUser(currentUser.getUserId());
    }
    if (this.save(entity)) {
      return entity.getId();
    }
    throw new Exception("成本月报保存失败");
  }

  /**
   * 更新成本月报
   * @param model 成本月报
   * @return 更新是否成功
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean update(MonthlyCostReportVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    MonthlyCostReport entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("成本月报不存在");
    }
    BeanUtils.copyProperties(
            model,
            entity,
            "id",
            "createTime",
            "createUser",
            "lastUpdateTime",
            "lastUpdateUser"
    );
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setLastUpdateUser(currentUser.getUserId());
    }
    return this.updateById(entity);
  }

  /**
   * 更新成本月报（带空值）
   * @param model 成本月报
   * @return 更新是否成功
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean updateForEdit(MonthlyCostReportVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    MonthlyCostReport entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("成本月报不存在");
    }
    model.setLastUpdateTime(new Date());
    if (currentUser != null) {
      model.setLastUpdateUser(currentUser.getUserId());
    }
    boolean isOk = new LambdaUpdateChainWrapper<>(baseMapper)
            .set(MonthlyCostReport::getOrgId, model.getOrgId())
            .set(MonthlyCostReport::getPeriodId, model.getPeriodId())
            .set(MonthlyCostReport::getStockId, model.getStockId())
            .set(MonthlyCostReport::getShopId, model.getShopId())
            .set(MonthlyCostReport::getItemId, model.getItemId())
            .set(MonthlyCostReport::getBeginQty, model.getBeginQty())
            .set(MonthlyCostReport::getBeginAmount, model.getBeginAmount())
            .set(MonthlyCostReport::getStockInQty, model.getStockInQty())
            .set(MonthlyCostReport::getStockInAmount, model.getStockInAmount())
            .set(MonthlyCostReport::getStockOutQty, model.getStockOutQty())
            .set(MonthlyCostReport::getStockOutAmount, model.getStockOutAmount())
            .set(MonthlyCostReport::getStockQty, model.getStockQty())
            .set(MonthlyCostReport::getStockAmount, model.getStockAmount())
            .set(MonthlyCostReport::getLastUpdateTime, model.getLastUpdateTime())
            .set(MonthlyCostReport::getLastUpdateUser, model.getLastUpdateUser())
            .eq(MonthlyCostReport::getId, model.getId())
            .update();
    return isOk;
  }

  /**
   * 删除成本月报
   * @param id 成本月报的主键
   * @return 删除是否成功
   */
  @Override
  public boolean delete(Long id) throws Exception {
    return this.removeById(id);
  }

  /**
   * 批量删除成本月报
   * @param ids 成本月报的主键列表
   * @return 删除是否成功
   */
  @Override
  public boolean batchDelete(List<Long> ids) throws Exception {
    return baseMapper.deleteBatchIds(ids) > 0;
  }

  /**
   * 导入单行处理
   * @param row 要导入的行
   * @param rowNumber 所在行号
   * @param vo 输出VO,可空
   * @param variables 变量池，用于在一次导入过程中保存临时信息
   * @return 导入行对象
   */
  protected ImportRow<MonthlyCostReportImportPo> excelToImportRow(
          MonthlyCostReportImportPo row,
          Integer rowNumber,
          MonthlyCostReportVo vo,
          Map<String, Object> variables
  ) {
    ImportRow<MonthlyCostReportImportPo> ir = new ImportRow<MonthlyCostReportImportPo>();
    ir.setRowNumber(rowNumber);
    ir.setRow(row);
    if (SheetUtils.isAllFieldsEmpty(row)) {
      ir.setEmptyRow(true);
      ir.addError("", "空行");
      return ir;
    }
    final Set<ConstraintViolation<MonthlyCostReportImportPo>> validate = validator.validate(
            row
    );
    boolean isOutputVo = vo != null;
    if (!isOutputVo) {
      vo = new MonthlyCostReportVo();
    }
    BeanUtils.copyProperties(row, vo);
    // 收集基本校验错误
    ir.initErrors(validate, MonthlyCostReportImportPo.class);

    // 一般数据处理
    vo.setOrgId(SheetUtils.tryToLong(row.getOrgId()));
    vo.setPeriodId(SheetUtils.tryToLong(row.getPeriodId()));
    vo.setStockId(SheetUtils.tryToLong(row.getStockId()));
    vo.setItemId(SheetUtils.tryToLong(row.getItemId()));
    vo.setBeginQty(SheetUtils.tryToInteger(row.getBeginQty()));
    vo.setBeginAmount(SheetUtils.tryToDecimal(row.getBeginAmount()));
    vo.setStockInQty(SheetUtils.tryToInteger(row.getStockInQty()));
    vo.setStockInAmount(SheetUtils.tryToDecimal(row.getStockInAmount()));
    vo.setStockOutQty(SheetUtils.tryToInteger(row.getStockOutQty()));
    vo.setStockOutAmount(SheetUtils.tryToDecimal(row.getStockOutAmount()));
    vo.setStockQty(SheetUtils.tryToInteger(row.getStockQty()));
    vo.setStockAmount(SheetUtils.tryToDecimal(row.getStockAmount()));

    return ir;
  }

  /**
   * 导入预览
   * @param sysFile 已上传到系统的文件
   */
  @Override
  public List<ImportRow<MonthlyCostReportImportPo>> importPreview(
          SysFile sysFile
  ) throws Exception {
    Map<String, Object> variables = new HashMap<>();
    try (InputStream in = fileService.read(sysFile)) {
      List<ImportRow<MonthlyCostReportImportPo>> rows = new ArrayList<>();

      // 读取 Excel 到 rows
      EasyExcel
              .read(
                      in,
                      MonthlyCostReportImportPo.class,
                      new ReadListener<MonthlyCostReportImportPo>() {
                        @Override
                        public void invoke(
                                MonthlyCostReportImportPo row,
                                AnalysisContext cxt
                        ) {
                          ImportRow<MonthlyCostReportImportPo> ir = excelToImportRow(
                                  row,
                                  cxt.readRowHolder().getRowIndex(),
                                  null,
                                  variables
                          );
                          if (ir.isEmptyRow()) {
                            return;
                          }
                          rows.add(ir);
                        }

                        @Override
                        public void doAfterAllAnalysed(AnalysisContext analysisContext) {}
                      }
              )
              .sheet()
              .doRead();

      return rows;
    }
  }

  /**
   * 完成导入
   * @param rows 预导入的行信息
   */
  @Transactional(rollbackFor = Exception.class)
  @Override
  public void importDone(List<ImportRow<MonthlyCostReportImportPo>> rows)
          throws Exception {
    Map<String, Object> variables = new HashMap<>();
    for (int i = 0; i < rows.size(); i++) {
      ImportRow<MonthlyCostReportImportPo> row = rows.get(i);
      MonthlyCostReportVo vo = new MonthlyCostReportVo();
      row = excelToImportRow(row.getRow(), row.getRowNumber(), vo, variables);
      if (row.getErrors() != null && row.getErrors().size() > 0) {
        throw new RException(
                String.format(
                        "第%d行（Excel第%d行）数据验证错误：%s",
                        i + 1,
                        row.getRowNumber(),
                        row.getJoinErrorMessage()
                )
        );
      }
      create(vo);
    }
  }

  /**
   * 导出
   * @param search 查询条件
   */
  @Override
  public void export(
          MonthlyCostReportSearchParamPo search,
          HttpServletResponse response
  ) throws Exception {
    search.setPageSize(EXPORT_QUERY_MAX_SIZE);
    int current = 1;
    List<MonthlyCostReportExcelPo> items = new ArrayList<MonthlyCostReportExcelPo>();
    while (true) {
      search.setCurrent(current);
      Page<MonthlyCostReportItemVo> page = this.pageSearch(search);
      if (page.getTotal() > EXPORT_MAX_SIZE) {
        throw new RException("导出记录数超出限制！");
      }
      List<MonthlyCostReportItemVo> list = page.getRecords();
      if (list.isEmpty()) {
        break;
      }
      for (MonthlyCostReportItemVo item : list) {
        MonthlyCostReportExcelPo excel = new MonthlyCostReportExcelPo();
        BeanUtils.copyProperties(item, excel);

        items.add(excel);
      }
      if (list.size() < EXPORT_QUERY_MAX_SIZE) {
        break;
      }
      current++;
    }

    ResponseUtils.setAttachmentFileName(response, "成本月报.xlsx");
    EasyExcel
            .write(response.getOutputStream())
            .sheet()
            .head(MonthlyCostReportExcelPo.class)
            .doWrite(items);
  }

  /**
   * 通过组织内码查询成本月报主键(重复时返回最新的主键)
   */
  @Override
  public Long getIdByOrgId(Integer orgId) {
    return this.baseMapper.getIdByOrgId(orgId);
  }

  /**
   * 通过组织内码查询成本月报多主键(重复时返回最新的主键)
   */
  @Override
  public List<Long> getIdsByOrgId(List<Integer> list) {
    return this.baseMapper.getIdsByOrgId(list);
  }

  /**
   * 通过成本月报主键查询组织内码
   */
  @Override
  public Integer getOrgIdById(Long id) {
    return this.baseMapper.getOrgIdById(id);
  }

  /**
   * 通过成本月报主键查询组织内码列表
   */
  @Override
  public List<Integer> getOrgIdByIds(List<Long> ids) {
    return this.baseMapper.getOrgIdByIds(ids);
  }

  /**
   * 获取详情
   * @param id 成本月报的主键
   */
  @Override
  public MonthlyCostReportVo getVoById(Long id) throws Exception {
    MonthlyCostReportVo vo = this.baseMapper.selectVoById(id);
    if (vo == null) {
      return null;
    }
    return vo;
  }

  /**
   * 分页查询成本月报
   * @param search 查询条件
   * @return 成本月报分页查询结果
   */
  @Override
  public Page<MonthlyCostReportItemVo> pageSearch(
          MonthlyCostReportSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    Page<MonthlyCostReportItemVo> page =
            this.baseMapper.pageSearch(search.toPage(), search);
    return page;
  }

  /**
   * 列表查询成本月报
   * @param search 查询条件
   * @return 成本月报列表查询结果
   */
  @Override
  public List<MonthlyCostReportItemVo> search(
          MonthlyCostReportSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.search(search);
  }

  /**
   * 查询成本月报最后更新时间
   * @param search 查询条件
   * @return 成本月报最后更新时间
   */
  @Override
  public Date searchLastUpdateTime(MonthlyCostReportSearchParamPo search) {
    return this.baseMapper.searchLastUpdateTime(search);
  }

  @Override
  public void saveOutBatch(List<StockVo> outList,Long periodId) {
    List<MonthlyCostReport> updateList=new ArrayList<>();
    for (StockVo stockVo : outList) {
      MonthlyCostReport entity = new MonthlyCostReport();
      BeanUtils.copyProperties(stockVo, entity);
      entity.setStockOutQty(stockVo.getQty());
      entity.setStockOutAmount(stockVo.getAmount());
      entity.setBeginQty(0-stockVo.getQty());
      entity.setBeginAmount(stockVo.getAmount().negate());
      entity.setCreateTime(new Date());
      entity.setLastUpdateTime(new Date());
      entity.setPeriodId(periodId);
    }
    this.saveBatch(updateList);
  }

  @Override
  public void saveInBatch(List<StockVo> inList ,Long periodId) {
    List<MonthlyCostReport> addList=new ArrayList<>();
    for (StockVo stockVo : inList) {
      MonthlyCostReport entity = new MonthlyCostReport();
      BeanUtils.copyProperties(stockVo, entity);
      entity.setBeginQty(stockVo.getQty());
      entity.setBeginAmount(stockVo.getAmount());
      entity.setCreateTime(new Date());
      entity.setLastUpdateTime(new Date());
      entity.setPeriodId(periodId);
      addList.add(entity);
    }
    this.saveBatch(addList);
  }

  @Override
  public void updateOutBatch(List<StockVo> out, Long periodId,Integer type) {
    if(out.size()<1000){
      this.baseMapper.updateOutBatch(out,periodId,type);
    }else {
      int fetchSize = 1000; //900条执行一IC  in orcale最大查询1000
      int listSize = out.size();
      for (int i = 0; i < out.size(); i += fetchSize) {
        if (i + fetchSize > listSize) {        //作用为toIndex最后没有100条数据则剩余几条newList中就装几条
          fetchSize = listSize - i;
        }
        List<StockVo> list = out.subList(i, i + fetchSize);
        if (CollectionUtils.isEmpty(list)) {
          continue;
        }
        this.baseMapper.updateOutBatch(list,periodId,type);
      }
    }
  }

  @Override
  public void insertCopys(Long periodId) {
    this.baseMapper.insertCopys(periodId);
  }

  @Override
  public List<MonthlyCostReportItemVo> getByModelPeriodId(String type, Long id) {
    return this.baseMapper.getByModelPeriodId(type,id);
  }

  @Override
  public void updateBatch(List<MonthlyCostReportItemVo> monthlyCostReportItemVos,String type) {
    if(monthlyCostReportItemVos.size()<1000){
      this.baseMapper.updateBatch(monthlyCostReportItemVos,type);
    }else {
      int fetchSize = 1000; //900条执行一IC  in orcale最大查询1000
      int listSize = monthlyCostReportItemVos.size();
      for (int i = 0; i < monthlyCostReportItemVos.size(); i += fetchSize) {
        if (i + fetchSize > listSize) {        //作用为toIndex最后没有100条数据则剩余几条newList中就装几条
          fetchSize = listSize - i;
        }
        List<MonthlyCostReportItemVo> list = monthlyCostReportItemVos.subList(i, i + fetchSize);
        if (CollectionUtils.isEmpty(list)) {
          continue;
        }
        this.baseMapper.updateBatch(list,type);
      }
    }


  }

  @Override
  public void insertBatch(List<MonthlyCostReport> insertCostReportList) {
       this.saveBatch(insertCostReportList);
  }

  @Override
  public void deleteByPeriodId(Long id) {
     this.baseMapper.deleteByPeriodId(id);
  }
}
